<?php

namespace Frieza\Modules\RiskContent\Actions;

use Doraemon\cache\Queue;
use Doraemon\cache\User as CacheUser;
use Doraemon\model\AdmOperateLog;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Doraemon\model\AdmRecommendUser;
use Doraemon\model\AdmBestUser;
use Doraemon\model\Member;
use Doraemon\service\Themis\Log as ThemisLog;
use Doraemon\model\Themis\Log as ThemisLogModel;

class Frozen extends RowAction
{
    public $name = '冻结';
    const TOAST_ALERT = '冻结此用户后，此用户将无法登陆，但此用户的数据依然存在。您确定要冻结此用户吗？';

    public function handle($uid)
    {
        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->username;
        //冻结用户的逻辑
        //删除用户在推荐表的数据
        AdmRecommendUser::deleteByUid($uid);
        //删除精华表数据
        AdmBestUser::deleteByUid($uid);
        //将用户的状态设置为冻结
        $member_data['status'] = Member::STATUS_FROZEN;
        $rst = Member::updateUserInfo($uid,$member_data);
        // 添加themis日志
        $aOpt = array(
            'admin_id'    => $admin_id,
            'remark'      => "该用户账号已被冻结",
            'status'      => ThemisLogModel::STATUS_FROZEN,
            'action_type' => ThemisLogModel::ACTION_TYPE_ADD_FROZEN,
            'illegal_or_punish' => ThemisLogModel::ACTION_PUNISH,
        );
        $aThemisLog = ThemisLog::fetchThemisLogData($uid, $aOpt);
        ThemisLog::add($aThemisLog);
        //删除token,强制退出登录
        Queue::insertQueue('User/frozen_user', array(
            'uid' => $uid,
        ), Queue::QUEUE_COMMON);
        Queue::insertQueue('User/delTokenCache', array(
            'uid' => $uid,
        ), Queue::QUEUE_COMMON);
        //删除cahce里面的缓存数据
        Queue::insertQueue('User/delUserinfoCache', array(
            'uid' => $uid,
        ), Queue::QUEUE_COMMON);
        if ($rst) {
            AdmOperateLog::addLog($uid,AdmOperateLog::$operate_type['frozen_user'],$admin_id,$admin_name);
            return $this->response()->success('已冻结该用户')->refresh();
        } else {
            return $this->response()->error('冻结失败,稍后重试!');
        }
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

     public function dialog()
     {
         $this->confirm(self::TOAST_ALERT);
     }
}
